package ru.michaeltyan.familyconnector.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import ru.michaeltyan.familyconnector.beans.FoodstuffList;
import ru.michaeltyan.familyconnector.beans.User;
import ru.michaeltyan.familyconnector.businessobjects.FoodstuffManagerBusinessObject;
import ru.michaeltyan.familyconnector.businessobjects.UserBusinessObject;

public class AuthorizationController implements Controller {

	protected final Log logger = LogFactory.getLog(getClass());

	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
		String login = (String) request.getParameter("login");
		String password = (String) request.getParameter("password");
		if (!("".equals(login) || "".equals(password))) {
			HttpSession session = request.getSession(true);
			ApplicationContext appContext = getAppContext(session);
			User user = findUser(login, appContext);
			if (user != null && user.getPassword().equals(password)) {
				ModelAndView modelAndView = createModelAndViewOfWelcomePage(login, appContext, user);
				return modelAndView;
			}
		} else {
			logger.error("Access denied.");
		}
		return new ModelAndView("authorization");
	}

	private ModelAndView createModelAndViewOfWelcomePage(String login, ApplicationContext appContext, User user) {
		logger.info("User " + login + " authorized.");
		ModelAndView modelAndView = new ModelAndView("welcome");
		modelAndView.addObject("user", user);
		FoodstuffManagerBusinessObject foodstuffManagerBo = (FoodstuffManagerBusinessObject) appContext.getBean("foodstuffManagerLFUBo");
		List<FoodstuffList> foodstuffLists = foodstuffManagerBo.findLists();
		modelAndView.addObject("foodstuffLists", foodstuffLists);
		return modelAndView;
	}

	private User findUser(String login, ApplicationContext appContext) {
		UserBusinessObject userBo = (UserBusinessObject) appContext.getBean("userBo");
		User user = userBo.findByLogin(login);
		return user;
	}

	private ApplicationContext getAppContext(HttpSession session) {
		ApplicationContext appContext;
		if (session.getAttribute("appContext") == null) {
			appContext = new ClassPathXmlApplicationContext("spring/config/BeanLocations.xml");
			session.setAttribute("appContext", appContext);
		} else {
			appContext = (ApplicationContext) session.getAttribute("appContext");
		}
		return appContext;
	}
}
